package wss

import (
	"github.com/gorilla/websocket"
	"net/http"
	"sync"
)

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

type HandlerFunc func(*websocket.Conn)

// webscoket收到消息
func OnMessage(handlerFunc func(*websocket.Conn, []byte, int, string), conn *websocket.Conn, msg []byte, msgtype int, roomCode string) {
	handlerFunc(conn, msg, msgtype, roomCode)
}

// Wensocket断开链接
func OnClose(handlerFunc func(*websocket.Conn, error, string), conn *websocket.Conn, err error, roomCode string) {
	handlerFunc(conn, err, roomCode)
}

// Websocket链接成功
func OnOpen(handlerFunc func(*websocket.Conn, string), conn *websocket.Conn, roomCode string) {
	handlerFunc(conn, roomCode)
}

// Websocket链接失败
func OnError(handlerFunc func(err error), err error) {
	handlerFunc(err)
}

// websocket初始化程序
func WsHandler(w http.ResponseWriter, r *http.Request, onOpen func(conn *websocket.Conn, roomCode string), onError func(err error), onClose func(*websocket.Conn, error, string), onMessage func(*websocket.Conn, []byte, int, string), roomCode string) {
	conn, err := upgrader.Upgrade(w, r, nil)
	//webscoket链接失败
	if err != nil {
		OnError(onError, err)
		return
	}
	//链接成功
	OnOpen(onOpen, conn, roomCode)
	go func() {
		var mutex sync.Mutex
		defer func() {
			conn.Close()
		}()
		for {
			mutex.Lock()
			msgType, msg, err := conn.ReadMessage()
			if err != nil {
				OnClose(onClose, conn, err, roomCode)
				return
			}
			switch msgType {
			//收到文本消息
			case websocket.TextMessage:
				OnMessage(onMessage, conn, msg, websocket.TextMessage, roomCode)
				//收到字节数组消息
			case websocket.BinaryMessage:
				OnMessage(onMessage, conn, msg, websocket.BinaryMessage, roomCode)
				//连接关闭消息
			case websocket.CloseMessage:
				OnClose(onClose, conn, err, roomCode)
				return
			}
			mutex.Unlock()
		}
	}()

}
